<script lang="ts" setup>
import { creatCouponPackOrderApi, postCreateOrderApi, postOrderSettlementApi } from '@/services/eat'
import { useDeviceStore, useMemberStore, usePhoneStore, useShoppingCartStore } from '@/stores'
import type { cartDataType } from '@/types/component'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { PageSkip, SwitchingDistance, Toast } from '@/utils/tools'

const shoppingCartStore = useShoppingCartStore()
const memberStore = useMemberStore()
const deviceStore = useDeviceStore()
const phoneStore = usePhoneStore()

let loading = ref(false)

const tmplIds = ref<string[]>([])
function getIsFirstOrder() {
  getIsFirstOrderApi().then((res) => {
    if (res?.data === 1) {
      tmplIds.value = [
        'gN9DKGzX7t6TdIdfN6OCqeBnW1_rq-M2SkPtOiuBP_M',
        'cvXN4cVzVAtR_H6kZz7CN-7CM_dp1cf7OtOW1S9ywcc',
        'WiLg6P_YrOaHXH8wj7BrYmqIkydnFkDfCm_7ymDnT2E',
      ]
    } else {
      tmplIds.value = [
        'gN9DKGzX7t6TdIdfN6OCqeBnW1_rq-M2SkPtOiuBP_M',
        'cvXN4cVzVAtR_H6kZz7CN-7CM_dp1cf7OtOW1S9ywcc',
      ]
    }
  })
}
function setting() {
  uni.getSetting({
    withSubscriptions: true,
    success(alwaysRes) {
      uni.requestSubscribeMessage({
        tmplIds: tmplIds.value, // 这里填写你的模板ID数组
        success(res: any) {
          if (res['gN9DKGzX7t6TdIdfN6OCqeBnW1_rq-M2SkPtOiuBP_M'] === 'accept') {
            // 用户同意订阅该模板
            console.log('用户同意订阅TEMPLATE_ID_1')
          }
          if (res['gN9DKGzX7t6TdIdfN6OCqeBnW1_rq-M2SkPtOiuBP_M'] === 'reject') {
            // 用户拒绝订阅该模板
            console.log('用户拒绝订阅TEMPLATE_ID_2')
          }
          if (res['cvXN4cVzVAtR_H6kZz7CN-7CM_dp1cf7OtOW1S9ywcc'] === 'accept') {
            // 用户同意订阅该模板
            console.log('用户同意订阅TEMPLATE_ID_1')
          }
          if (res['cvXN4cVzVAtR_H6kZz7CN-7CM_dp1cf7OtOW1S9ywcc'] === 'reject') {
            // 用户拒绝订阅该模板
            console.log('用户拒绝订阅TEMPLATE_ID_2')
          }
          if (res['WiLg6P_YrOaHXH8wj7BrYmqIkydnFkDfCm_7ymDnT2E'] === 'accept') {
            // 用户同意订阅该模板
            console.log('用户同意订阅优惠券发放通知')
          }
          if (res['WiLg6P_YrOaHXH8wj7BrYmqIkydnFkDfCm_7ymDnT2E'] === 'reject') {
            // 用户拒绝订阅该模板
            console.log('用户拒绝订阅优惠券发放通知')
          }
        },
        fail(err) {
          console.error('订阅消息失败', err)
        },
      })
    },
  })
}
/**
 * * 创建预支付订单接口
 */
const PrepaymentOrder = async () => {
  loading.value = true
  try {
    const res = await postCreateOrderApi({
      machineId: deviceStore.deviceInfo!.machineId,
      machineName: deviceStore.deviceInfo!.machineName,
      shoppingCartList: shoppingCartStore.shoppingCartInfo.map((item) => {
        return {
          machineId: deviceStore.deviceInfo!.machineId,
          packageId: item.packageId,
          packageName: item.packageName,
          quantity: item.count,
        }
      }),
      clientCouponId: couponInfo.value?.id! > 0 ? couponInfo.value?.id : null,
    })
    loading.value = false
    if (res.data.couponType === 5 && res.code === 200) {
      PageSkip(
        `/pagesGoods/goodsDetails/goodsDetails?orderId=${res.data.orderId}&flag=${true}`,
        'redirectTo',
      )
      shoppingCartStore.clearShoppingCartInfo()
      // setting()
    } else if (res.code === 200) {
      const item = JSON.stringify({
        orderId: res.data.orderId,
        paidPrice: res.data.paidPrice,
        saleEndTime: res.data.saleEndTime,
      })
      PageSkip(`/pagesGoods/cashierDesk/cashierDesk?item=${item}`, 'redirectTo')
      shoppingCartStore.clearShoppingCartInfo()
      // setting()
    } else {
      Toast(res.msg || '库存不足')
    }
  } catch (error) {
    loading.value = false
  }
}

// 去支付
const goPay = () => {
  if (couponPackInfo.value.type === 'couponPack') {
    creatCouponPackOrder()
  } else {
    PrepaymentOrder()
  }
}
/**
 * * 创建预支付订单接口
 */
const creatCouponPackOrder = async () => {
  loading.value = true
  try {
    console.log('couponPackInfo.value', couponPackInfo.value)
    const res = await creatCouponPackOrderApi({
      machineId: deviceStore.deviceInfo!.machineId,
      comboDTOS: {
        id: couponPackInfo.value.id,
        num: 1,
      },
    })
    loading.value = false
    console.log('res', res)
    if (res.code === 200 && res.data) {
      couponPackInfo.value.orderId = res.data
      PageSkip(
        `/pagesGoods/cashierDesk/cashierDesk?item=${JSON.stringify(
          couponPackInfo.value,
        )}&type=couponPack&orderId=${res.data}`,
        'redirectTo',
      )
    } else {
      Toast(res.msg || '库存不足')
    }
  } catch (error) {
    loading.value = false
  }
}

// 实付价格
const paidPrice = computed(() => {
  return shoppingCartStore.shoppingCartInfo.reduce((prev: number, next: cartDataType) => {
    return prev + next.count * parseFloat(next.deviceAmount)
  }, 0)
})
/**
 * * 跳转地图
 */
const skipMapFn = () => {
  uni.openLocation({
    latitude: Number(deviceStore.deviceInfo?.latitude),
    longitude: Number(deviceStore.deviceInfo?.longitude),
    success: () => {
      console.log('成功进入跳转地图')
    },
  })
}
type couponType = {
  couponId?: null | number
  discountMoney?: null | number
  couponName?: null | string
  discounts?: null | string
  discountsType?: null | number
  validEndTime?: null | string
  id: null | number
  discountedAfterPrice?: null | number
}
const couponInfo = ref<couponType>({
  couponId: null,
  discountMoney: null,
  couponName: null,
  discounts: null,
  discountsType: null,
  validEndTime: null,
  id: null,
  discountedAfterPrice: null,
})
const couponPackInfo = ref<any>({})
const isBack = ref(false)
// 涉及到页面进入优惠券，再返回到当前页面
onShow(() => {
  let curPages: any = getCurrentPages()
  // 接受页面返回传过来的参数
  uni.$once('navigateBack', (data) => {
    couponInfo.value.id = Number(data.id)
  })
  isBack.value = curPages[curPages.length - 1].options?.back ? true : false
  if (curPages[curPages.length - 1]?.options?.id) {
    couponInfo.value.id = Number(curPages[curPages.length - 1].options.id)
  }
  if (curPages[curPages.length - 1].options.type === 'couponPack') {
    couponPackInfo.value = JSON.parse(curPages[curPages.length - 1].options.couponPackInfo)
    couponPackInfo.value.type = curPages[curPages.length - 1].options.type
    return
  }
  getOrderInfo()
  getAwaitNum()
  getIsFirstOrder()
})
import { getAwaitNumApi } from '@/services/eat'
import { getIsFirstOrderApi } from '@/services/home'
const awaitNum = ref(0)
/** 获取排队信息 */
const getAwaitNum = async () => {
  const res = await getAwaitNumApi({ machineId: deviceStore.deviceInfo!.machineId })
  awaitNum.value = res.data || 0
}
/** 获取订单信息 */
const getOrderInfo = async () => {
  const res = await postOrderSettlementApi({
    machineId: deviceStore.deviceInfo!.machineId,
    machineName: deviceStore.deviceInfo!.machineName,
    clientCouponId: couponInfo.value?.id! > 0 ? couponInfo.value?.id : null,
    shoppingCartList: shoppingCartStore.shoppingCartInfo.map((item) => {
      console.log(item)
      return {
        machineId: deviceStore.deviceInfo!.machineId,
        packageId: item.packageId,
        packageName: item.packageName,
        quantity: item.count,
      }
    }),
  })
  couponInfo.value = res.data || {}
}
/**跳转页面，并且压缩传值 */
const skipPage = () => {
  const detailsCoupon = {
    id: couponInfo.value?.id,
    machineId: deviceStore.deviceInfo!.machineId,
    priceOriginal: paidPrice.value,
    shoppingCartList: shoppingCartStore.shoppingCartInfo.map((item) => {
      return {
        machineId: deviceStore.deviceInfo!.machineId,
        packageId: item.packageId,
        quantity: item.count,
      }
    }),
  }
  console.log(detailsCoupon)
  const params = encodeURIComponent(JSON.stringify(detailsCoupon))
  PageSkip(`/pagesMy/userCoupon/userCoupon?params=${params}`)
}
/** 返回吃饭页面 */
const onBack = () => {
  if (isBack.value) {
    uni.navigateBack()
    return
  }
  PageSkip('/pages/eat/eat', 'switchTab')
}
</script>

<template>
  <!-- 头部导航栏 -->
  <view
    class="headNavigationBar"
    :style="{ height: Number(phoneStore.phoneInfo?.bottom) + 6 + 'px' }"
  >
    <text class="iconfont icon-left" @tap="onBack()"></text>
    <text class="navTitle">订单结算</text>
  </view>
  <!-- 设备信息 -->
  <view class="devicePoint">
    <view class="devicePointLeft">
      <view class="name"
        >{{ deviceStore.deviceInfo?.machineName }}
        <view class="position"
          ><image src="/static/images/billingPage/location.png" mode="scaleToFill" /> 距离您{{
            SwitchingDistance(deviceStore.deviceInfo?.distanceCenterPoint + 'm')
          }}
        </view></view
      >
      <view class="address">{{ deviceStore.deviceInfo?.positionAddr }} </view>
    </view>
  </view>
  <view class="_production" v-if="awaitNum && !couponPackInfo.type">
    <view class="productionBox"
      >前方
      <view class="_num">{{ awaitNum }}</view>
      份制作中，请耐心等待</view
    >
  </view>
  <view class="_production" v-if="!awaitNum && !couponPackInfo.type">
    <view class="productionBox">现在下单，立即制作</view>
  </view>
  <!-- 商品价格 -->
  <view class="myGoods" v-if="!couponPackInfo.type">
    <!-- 循环渲染盒子 -->
    <view class="goodsBox">
      <view
        class="goodsItem"
        v-for="item in shoppingCartStore.shoppingCartInfo"
        :key="item.packageId"
      >
        <image class="image" :src="item.thumbUrl" mode="scaleToFill" />
        <view class="setMeal">
          <view class="setMealName">{{ item.packageName }}</view>
          <view class="setMealSpecification">{{ item.packageName }} | 餐具</view>
        </view>
        <view class="price">
          <text class="discountPrice"
            ><text class="icon">￥</text>{{ Number(item.deviceAmount).toFixed(2) }}</text
          >
          <!-- <text class="originalPrice">￥{{ Number(item.deviceAmount).toFixed(2) }}</text> -->
          <text class="number">×{{ item.count }}</text>
        </view>
      </view>
    </view>
    <!-- 计算部分 -->
    <view class="compute">
      <view class="goodsDisPrice">
        <view class="goodsDisPriceText">商品总额</view>
        <view class="goodsDisPriceNumber">￥{{ paidPrice.toFixed(2) }}</view>
      </view>
      <!-- 优惠券部分 -->
      <view @tap.stop="skipPage()" class="coupon">
        <view class="couponText">优惠券</view>
        <view class="couponTips" v-if="couponInfo?.discountMoney">
          <view class="couponName">{{ couponInfo?.couponName }}</view>
          <view class="couponPrice">-￥{{ Number(couponInfo?.discountMoney).toFixed(2) }}</view>
          <text class="iconfont icon_arrow-left-1"></text>
        </view>
        <view v-else class="couponTips">
          <view class="noData">暂无可用优惠券</view>
          <text class="iconfont icon_arrow-left-1"></text>
        </view>
      </view>
    </view>
    <!-- 实付价格部分 -->
    <view class="paidPrice">
      <view class="paidPrice_1" v-if="couponInfo?.discountMoney! > 0">已优惠</view>
      <view class="paidPrice_2" v-if="couponInfo?.discountMoney! > 0"
        >￥{{ couponInfo?.discountMoney!.toFixed(2) }}</view
      >
      <view class="paidPrice_3">合计</view>
      <view class="paidPrice_4"
        ><text class="icon">￥</text>{{ (paidPrice - couponInfo?.discountMoney!).toFixed(2) }}</view
      >
    </view>
  </view>
  <view class="myGoods" v-else>
    <!-- 循环渲染盒子 -->
    <view class="goodsBox">
      <view class="goodsItem">
        <image class="image" :src="couponPackInfo.shopImg" mode="scaleToFill" />
        <view class="setMeal">
          <view class="setMealName">{{ couponPackInfo.name }}</view>
        </view>
        <view class="price">
          <text class="discountPrice"><text class="icon">￥</text>{{ couponPackInfo.price }}</text>
          <text class="number">×1</text>
        </view>
      </view>
    </view>
    <!-- 计算部分 -->
    <view class="compute">
      <view class="goodsDisPrice">
        <view class="goodsDisPriceText">商品总额</view>
        <view class="goodsDisPriceNumber">￥{{ couponPackInfo.price }}</view>
      </view>
    </view>
    <!-- 实付价格部分 -->
    <view class="paidPrice">
      <view class="paidPrice_3">合计</view>
      <view class="paidPrice_4">￥{{ couponPackInfo.price }}</view>
    </view>
  </view>
  <view class="pay" v-if="!couponPackInfo.type">
    <view class="payLeft">
      <view class="actualPayment">
        <view class="actualPaymentText">合计</view>
        <view class="actualPaymentPrice"
          >￥{{ (paidPrice - couponInfo?.discountMoney!).toFixed(2) }}</view
        >
      </view>
      <view class="sumDiscount" v-if="couponInfo?.discountMoney! > 0"
        >总计优惠￥{{ couponInfo?.discountMoney!.toFixed(2) }}</view
      >
    </view>
    <view class="payRight">
      <button class="goToPay" :loading="loading" :disabled="loading" @tap="PrepaymentOrder()">
        去支付
      </button>
    </view>
  </view>
  <view class="pay" v-else>
    <view class="payLeft">
      <view class="actualPayment">
        <view class="actualPaymentText">合计</view>
        <view class="actualPaymentPrice">￥{{ couponPackInfo.price }}</view>
      </view>
    </view>
    <view class="payRight">
      <button class="goToPay" :loading="loading" :disabled="loading" @tap="goPay">去支付</button>
    </view>
  </view>
</template>

<style lang="scss">
//
page {
  height: 100vh;
  background-color: #f5f5f5;
}
// 设备信息
.devicePoint {
  display: flex;
  justify-content: space-between;
  padding: 42rpx 36rpx;
  margin: 30rpx 30rpx 0;
  width: 690rpx;
  height: 176rpx;
  border-radius: 16rpx;
  background-color: #fff;
  box-shadow: 0rpx 4rpx 198rpx 2rpx rgba(0, 0, 0, 0.05);
  .devicePointLeft {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    font-size: 28rpx;
    color: #000;
    .name {
      font-size: 32rpx;
      font-weight: bold;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .position {
        font-weight: normal;
        font-size: 26rpx;
        color: #ffa407;
        margin-left: 16rpx;
        display: flex;
        align-items: center;
        image {
          width: 24rpx;
          height: 24rpx;
          margin-right: 8rpx;
        }
      }
    }
    .address {
      margin-top: 8rpx;
      font-size: 26rpx;
      color: #aaa;
    }
  }
  .devicePointRight {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    & ._image {
      margin-top: 8rpx;
      width: 80rpx;
      height: 80rpx;
    }
  }
}
// 计算商品价格
.myGoods {
  margin: 20rpx 30rpx 0;
  padding: 24rpx;
  width: 690rpx;
  border-radius: 20rpx;
  background-color: #fff;
}
// 制作提示

._production {
  margin: 20rpx 30rpx;
  width: 690rpx;
  .productionBox {
    display: flex;
    width: 100%;
    height: 76rpx;
    line-height: 76rpx;
    border-radius: 16rpx;
    background-color: #fff;
    padding-left: 48rpx;
    color: #000;
    font-size: 24rpx;
    ._num {
      font-size: 28rpx;
      font-weight: bold;
      margin: 0 6rpx;
      color: $uni-color-motif;
    }
  }
}

// 商品循环 item
.goodsItem {
  display: flex;
  margin-bottom: 28rpx;
  background: #f8f8f8;
  padding: 24rpx 20rpx 24rpx 40rpx;
  border-radius: 20rpx;
  align-items: center;
  .image {
    width: 120rpx;
    height: 120rpx;
    border-radius: 20rpx;
  }
  .setMeal {
    flex: 1;
    margin: 0 20rpx;
    white-space: nowrap; /* 不换行 */
    overflow: hidden; /* 超出部分隐藏 */
    text-overflow: ellipsis; /* 显示省略号 */
    .setMealName {
      font-size: 30rpx;
      color: #212121;
      white-space: nowrap; /* 不换行 */
      overflow: hidden; /* 超出部分隐藏 */
      text-overflow: ellipsis; /* 显示省略号 */
    }
    .setMealSpecification {
      margin-top: 8rpx;
      font-size: 24rpx;
      color: #cccccc;
      white-space: nowrap; /* 不换行 */
      overflow: hidden; /* 超出部分隐藏 */
      text-overflow: ellipsis; /* 显示省略号 */
    }
  }
  .price {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    width: 120rpx;
    .discountPrice {
      font-size: 30rpx;
      color: #000000e5;
    }
    .originalPrice {
      margin-top: 4rpx;
      font-size: 24rpx;
      color: #0000004d;
      text-decoration: line-through;
    }
    .number {
      margin-top: 4rpx;
      font-size: 24rpx;
      color: #0000004d;
    }
  }
}
// 优惠券计算部分
.compute {
  display: flex;
  flex-direction: column;
  border-bottom: 1px dashed #0000001a;
  padding-top: 28rpx;
  .goodsDisPrice,
  .goodsOriPrice,
  .coupon {
    display: flex;
    justify-content: space-between;
    margin-bottom: 32rpx;
    height: 34rpx;
    font-size: 28rpx;
    .goodsDisPriceText,
    .couponText {
      color: #696969;
    }
  }
}
// 优惠券默认使用部分
.couponTips {
  display: flex;
  justify-content: center;
  align-items: center;
  .couponName {
    display: flex;
    align-items: center;
    font-size: 20rpx;
    padding: 4rpx 8rpx;
    border-radius: 6rpx;
    color: #fff;
    background-color: #fa5151;
  }
  .couponPrice {
    font-size: 24rpx;
    margin: 0 16rpx;
  }
  .iconfont {
    font-size: 20rpx;
    color: #00000080;
  }
  .noData {
    font-size: 24rpx;
    color: #b3b3b3;
  }
}
// 实付价格
.paidPrice {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 28rpx;
  height: 42rpx;
  font-size: 24rpx;
  .paidPrice_1 {
    color: #00000080;
  }
  .paidPrice_3 {
    margin-left: 12rpx;
    color: #000000e5;
  }
  .paidPrice_4 {
    font-size: 30rpx;
    color: #000000;
  }
}
// 红字
.paidPrice_2,
.couponPrice,
.goodsOriPriceNumber,
.sumDiscount {
  color: #fa5151;
}
// 支付定位模块
.pay {
  position: fixed;
  display: flex;
  bottom: 0;
  justify-content: space-between;
  padding: 20rpx 24rpx 56rpx 24rpx;
  width: 100%;
  background-color: #fff;
  .payLeft {
    .actualPayment {
      display: flex;
      align-items: center;
      .actualPaymentText {
        font-size: 30rpx;
        color: #000000e5;
      }
      .actualPaymentPrice {
        font-size: 36rpx;
        color: #000;
      }
    }
    .sumDiscount {
      font-size: 22rpx;
    }
  }
  .payRight {
    .goToPay {
      width: 280rpx;
      height: 80rpx;
      line-height: 80rpx;
      font-size: 32rpx;
      border-radius: 200rpx;
      color: #000;
      background-color: $uni-color-motif;
    }
  }
}

.headNavigationBar {
  position: relative;
  z-index: 999;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: flex-end;
  font-size: 32rpx;
  background: #fff;
  color: #000000e5;
  padding-bottom: 22rpx;
  .iconfont {
    position: absolute;
    left: 10rpx;
    bottom: 22rpx;
    width: 100rpx;
    font-size: 42rpx;
    padding-left: 14rpx;
  }
  .navTitle {
    font-size: 32rpx;
  }
}
.icon {
  color: $uni-color-motif;
}
</style>
